from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.permissions import IsAuthenticated

from apps.activities.serializers import GatherSerializer
from apps.activities.models import Gathering


# Create your views here.

# 活动列表
from apps.activities.utils import PageNum


class GatherViewSet(ListModelMixin, GenericAPIView):
    '''视图'''
    queryset = Gathering.objects.all()

    serializer_class = GatherSerializer

    pagination_class = PageNum

    def get(self, request):

        return self.list(request)


# 活动详情
from rest_framework.views import APIView
class GatherDetailsView(RetrieveModelMixin, GenericAPIView):

    queryset = Gathering.objects.all()

    serializer_class = GatherSerializer

    def get(self, request, pk):

        return self.retrieve(request)


#参加或者取消活动
class GatherJoinView(GenericAPIView):
    # 指定查询集
    queryset = Gathering.objects.all()
    # 设置参加.取消活动权限
    permission_classes = [IsAuthenticated]
    def post(self, request, pk):
        user = request.user
        gathering = self.get_object()

        if user in gathering.users.all():
            gathering.users.remove(user)
            gathering.save()
            return Response({'success': True, 'message': '取消成功'})
        else:
            gathering.users.add(user)
            gathering.save()
            return Response({'success':True,'message':'参加成功'})

